#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>

#define PORT 8080
#define BACKLOG 32

int main()
{
    struct sockaddr_in server_addr;
    int server_fd;

    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        exit(-1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int on = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int));
    if (bind(server_fd, &server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind");
        exit(-1);
    }

    if (listen(server_fd, BACKLOG) < 0)
    {
        perror("listen");
        exit(-1);
    }

    // accept数据
    struct sockaddr_in client;
    int sockadd_in_len = sizeof(struct sockaddr_in);
    int client_fd;

    while (1)
    {
        if ((client_fd = accept(server_fd, &client, &sockadd_in_len)) < 0)
        {
            perror("accept");
            continue;
        }

        if (!fork())
        {
            // 子进程
            char buffer[1024];
            while (1)
            {
                int rec_len = recv(client_fd, buffer, 1024, 0);
                if (rec_len <= 0)
                {
                    return 0;
                }
                buffer[rec_len] = 0;
                printf("receive: %s from client %s!\n", buffer, inet_ntoa(client.sin_addr));
            }
        }
    }

    return 0;
}
